/**
 * Company : SIANGKLOM.
 * Created By : Chatree Siangklom
 * Created On : Sep 18, 2013  4:30:50 PM 
 * e-Mail : dr_chatree@hotmail.com
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : com.tis.interfaces.controller.sd.outbound.sales
 * File Name : CustomerController.java
 * TODO
 */
package com.tis.interfaces.controller.sd.outbound.sales;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import promis.db.connection.Userinfo;
import promis.utility.CommonService;
import sap.business.commons.SapMessageReturn;
import sap.business.enumeration.Module;
import sap.business.enumeration.ResultStatus;
import sap.business.enumeration.STAGING_STATUS;
import sap.business.sd.outbound.CustomerInterServices;
import com.tis.database.entitys.SapMessage;
import com.tis.database.entitys.promis.Customer;
import com.tis.database.entitys.promis.VwSyncCustomer;
import com.tis.database.entitys.security.AdUserLogin;
import com.tis.database.entitys.staging.ApplicationLoging;
import com.tis.database.entitys.staging.SdCustomerOutb1;
import com.tis.database.entitys.staging.XmlResultback;
import com.tis.database.services.ISyncAppsHostServices;
import com.tis.database.services.promis.ICustomerServices;
import com.tis.database.services.promis.IVwSyncCustomerServices;
import com.tis.database.services.staging.ISdCustomerOutb1Services;
import com.tis.interfaces.controller.commons.CommonController;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Sep 18, 2013 : 4:30:50 PM 
 * CreateBy=Chatree Siangklom
 * TODO
 */
@Controller
@RequestMapping(value=CustomerController.url)
public class CustomerController extends CommonController {

	private static final Logger logging = LoggerFactory.getLogger(CustomerController.class);
	public static final String  url = "/sd/outbound/sales/customer";
	public static final String  uri = "/sd/outbound/sales";	
	
	@Autowired IVwSyncCustomerServices iVwSyncCustomerServices;
	@Autowired ICustomerServices iCustomerServices;
	@Autowired ISdCustomerOutb1Services iSdCustomerOutb1Services;
	
	@Autowired
	private ISyncAppsHostServices iSyncAppsHostServices;
	
	@RequestMapping(value="index")
	public String Index(HttpServletRequest request, Model model) throws Exception {
		logging.info("/sd/outbound/sales/customer/index {Index}");
		
		logging.info("Size=" + CommonService.getSize(iSyncAppsHostServices.findByCode("AUTHEN_KEY", "Y", "NSTDA")));
		
		try {
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			//Put History
			try { UserAccessTime(request, this.toString()); }catch(Exception e) {e.printStackTrace();}
			
			if(!UserLoginValidation((request)))
				return "redirect:/login";
			
			CustomerForm form = new CustomerForm();
			form.setSyncCreatedOnStart(CommonService.ConvertDateToString(new Date()));
			form.setSyncCreatedOnEnd(CommonService.ConvertDateToString(new Date()));
			form.setMaxResult("5000");
			
			logging.info("form =" + form.toString());
			model.addAttribute("ObjectForm", form);
			
		} catch (Exception e) {
			logging.error(e.getMessage());
			e.printStackTrace();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", e.getMessage(), null, getCurrentAppsInstanceNo()));
			throw e;
		}
		
		return uri + "/customer";
	}
	
	@RequestMapping(value="search", method = RequestMethod.POST)
	public String Search(HttpServletRequest request, Model model, @ModelAttribute("ObjectForm") @Valid	CustomerForm form, BindingResult result) throws Exception {
		try {
			logging.info("/sd/outbound/sales/customer/search {search}");
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			//Put History 		
			try { UserAccessTime(request, this.toString()); }catch(Exception e) {e.printStackTrace();}
			
			if(!UserLoginValidation((request)))
				throw new Exception("Can't Search, Please Login first !!!!");
			
		} catch (Exception e) {
			e.printStackTrace();
			logging.error(e.getMessage());
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", e.getMessage(), null, getCurrentAppsInstanceNo()));
			
			throw e;
		}
		
		return uri + "/customer";
	}
	
	//INVOICES  - Invoice, Debit Note
	//PMS_PAYMENTS_RECEIVED - Receive
	//CUSTOMER_CREDIT_NOTES - Credit Note
	//PAYMENT_VOUCHERS - Deposit Return
	//interfacekey=84MlQYjqHe1sT3D5oP6q1xwKOoJ5fsaR85MXOGJUn4OCnw8YcnQK0u6C02ar59jrkC5{||5||}QLusNTuoXnOKqIbYU{||9||}QeSzufWivdcezXOKUJ9Bnnf9c086p5J4sjsSZwDDYFn0OiEA{||9||}Ga6qa39w{||9||}ZRWh9g{||4||}{||4||}	
	@RequestMapping(value="interface", method = RequestMethod.GET)
	public HttpEntity<byte[]> Interface(	
													@RequestParam(value="interfacekey", required=true) String interfacekey,
													@RequestParam(value="instanceNo", required=true) String instanceNo,
													Model model,
													HttpServletRequest request, 
													HttpServletResponse response) throws Exception {
		logging.info("/sd/outbound/sales/customer/interface {interface}");
		logging.info("instanceNo=" + instanceNo);
		logging.info("interfacekey=" + interfacekey);
		
		setCurrentAppsInstanceNo();
		System.out.println("currentAppsInstanceNo=" + getCurrentAppsInstanceNo());
		
		KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));	
		XmlResultback  xmlResultback = new XmlResultback(Module.CUSTOMER.toString(), getCurrentAppsInstanceNo(), iSdCustomerOutb1Services.getCurrentDatabaseDate());
		try {
			
			//Put History 		
			try { UserAccessTime(request, this.toString()); }catch(Exception e) {e.printStackTrace();}
			
			if(CommonService.IsNull(interfacekey)){
				xmlResultback.setMsgcode(STAGING_STATUS.EE.toString());
				xmlResultback.setMsgDescription("Authentication Key is fail !!!");
				return ToXml(xmlResultback);
			}
			
			AdUserLogin adUserLoin =  AuthenOfPromis(interfacekey);
			if(adUserLoin != null){
				//Search Customer list by InstanceNo
				List<SdCustomerOutb1> lst = iSdCustomerOutb1Services.findByInstanceNo(instanceNo, new SdCustomerOutb1());
				logging.info("SdCustomerOutb1 size=" + CommonService.getSize(lst));
				if(CommonService.getSize(lst) > 0){
					try{

						List<SdCustomerOutb1> lst1 = new ArrayList<>();
						for(SdCustomerOutb1 sdCustomerOutb1 : lst){
							SdCustomerOutb1 cusOutb1 = sdCustomerOutb1;
							
							 List<String> nameLst = iSdCustomerOutb1Services.NameSplitToSAP(sdCustomerOutb1.getName1());
							 cusOutb1.setName1(nameLst.get(0));
							 cusOutb1.setName2(nameLst.get(1));
							 cusOutb1.setName3(nameLst.get(2));
							 cusOutb1.setName4(nameLst.get(3));
							 
							 List<String> streetLst = iSdCustomerOutb1Services.NameSplitToSAP(sdCustomerOutb1.getStreet());
							 cusOutb1.setStreet(streetLst.get(0));
							 cusOutb1.setStreet4(streetLst.get(1));
							 
							 lst1.add(cusOutb1);
						}
						
						SapMessageReturn<SdCustomerOutb1> sapMessageReturn = new CustomerInterServices().SynchroToSap(lst1);
						
						if(sapMessageReturn != null){
							ResultStatus resultStatus = sapMessageReturn.getResultBacked().getResultStatus();
							if(resultStatus != null){
								List<SapMessage> sapMessageList = sapMessageReturn.getOutput();
								
								logging.info("sapMessageList size=" + CommonService.getSize(sapMessageList));
								if(CommonService.getSize(sapMessageList) > 0)
								{
									SapMessage sapMsg = sapMessageList.get(0);
									logging.info("SapMessage toString=" + sapMsg.toString());
									xmlResultback.setMsgcode(sapMsg.getMsgCode());
									xmlResultback.setMsgDescription(sapMsg.getMsgDesc());
									xmlResultback.setExtRefNo(sapMsg.getExtRefNo());
									xmlResultback.setExtRefKey(sapMsg.getExtRefKey());
								}
							}
							
							//Step Update Message to Staging Table
							List<SdCustomerOutb1> lstResultBack = iSdCustomerOutb1Services.UpdateBackSapMessage(sapMessageReturn.getOutput());
							logging.info("lstResultBack size=" + CommonService.getSize(lstResultBack));
							
							//Step Update Back to Promis Table
							try{
								if(CommonService.getSize(lstResultBack) > 0){
									Customer obj = iCustomerServices.findById(lstResultBack.get(0).getCustomer());
									if(obj != null)
									{
										obj.setSyncIsstaging("Y");
										obj.setSyncIssync("N");
										obj.setResendCount(obj.getResendCount() + 1);
										if(CommonService.IsNullRString(lstResultBack.get(0).getMsgCode()).equals("PS")){					
											obj.setSyncIssync("Y");	
										}
										
										iCustomerServices.saveOrUpdate(obj);
									}
								}
							}catch(Exception ex){
								ex.printStackTrace();
								xmlResultback.setMsgcode("EE");
								xmlResultback.setMsgDescription("" + ex.getMessage());
								logging.error(ex.getMessage());
								iSdCustomerOutb1Services.SaveErrorToStaging(getCurrentAppsInstanceNo(), STAGING_STATUS.EE, ex.getMessage());
								KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", ex.getMessage(), null, getCurrentAppsInstanceNo()));									
							}
						}
					}catch(Exception  ee){
						ee.printStackTrace();
						xmlResultback.setMsgcode(STAGING_STATUS.EE.toString());
						xmlResultback.setMsgDescription(ee.getMessage());
						
						KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", ee.getMessage(), null, getCurrentAppsInstanceNo()));
					}
				}else{
					xmlResultback.setMsgcode(STAGING_STATUS.EE.toString());
					xmlResultback.setMsgDescription("Data not found. Criteria: [instanceNo="+ instanceNo +"] !!!");
				}
			}else{
				xmlResultback.setMsgcode(STAGING_STATUS.EE.toString());
				xmlResultback.setMsgDescription("Authentication is fail !!!");
				
				response.setStatus(406);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logging.error(e.getMessage());
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", e.getMessage(), null, getCurrentAppsInstanceNo()));
			
			xmlResultback.setMsgcode(STAGING_STATUS.EE.toString());
			xmlResultback.setMsgDescription(e.getMessage());
		}
		
		return ToXml(xmlResultback);
	}
	
	@RequestMapping(value="resend", method = RequestMethod.GET)
	@ResponseBody 
	public HttpEntity<byte[]> ReSend(	@RequestParam(value="interfacekey", required=true) String interfacekey,
										@RequestParam(value="customerCode", required=true) String customerCode,
										@RequestParam(value="processAction", required=false, defaultValue="") String processAction,
										Model model,
										HttpServletRequest request, 
										HttpServletResponse response) throws HibernateException, Exception {
		logging.info("welcome resend --------------------->");
		setCurrentAppsInstanceNo();
		System.out.println("currentAppsInstanceNo=" + getCurrentAppsInstanceNo());
		
		XmlResultback  xmlResultback = new XmlResultback(Module.CUSTOMER.toString(), getCurrentAppsInstanceNo(), iSdCustomerOutb1Services.getCurrentDatabaseDate());
		KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
		
		try{
			logging.info("customerCode="+ customerCode + "// interfacekey="+ interfacekey);
			
			//Put History 		
			try { UserAccessTime(request, this.toString()); }catch(Exception e) {e.printStackTrace();}
			
			if(CommonService.IsNull(interfacekey)){
				xmlResultback.setMsgcode(STAGING_STATUS.EE.toString());
				xmlResultback.setMsgDescription("Authentication Key is fail !!!");
				return(ToXml(xmlResultback));
			}
			
			AdUserLogin adUserLoin =  AuthenOfPromis(interfacekey);
			if(adUserLoin != null){
				List<SdCustomerOutb1> lstx = new ArrayList<SdCustomerOutb1>();
				List<VwSyncCustomer> customerls = iVwSyncCustomerServices.Search(customerCode, null, null, null, null, null, 0);
				for(VwSyncCustomer value : customerls){
					logging.info("VwSyncCustomer:" + value.toString());
					
					SdCustomerOutb1 obj = new SdCustomerOutb1();
					obj.setAccountgroup(value.getAccountGroup());
					obj.setCity(value.getProvinceName());
					obj.setCountry(value.getCountryCode());
					obj.setCreateby(value.getCreatedBy());
					obj.setCreateon(CommonService.ConvertDateToSAPStringDate(value.getCreatedOn()));
					obj.setCusStatusGrp(value.getCusStatusGrp());
					obj.setCustomer(value.getCustomerCode());
					obj.setCustomergroup(value.getCustomerGroup());
					obj.setDistributionchannel(value.getDistributionChannel());
					obj.setDistrict(value.getAmphurName());
					obj.setDivision(value.getDivision());
					obj.setDunprocedure(value.getDunprocedure());
					obj.setEmail(value.getEmail());
					obj.setExtRefKey(value.getSyncExternalRefKey());
					obj.setExtRefNo(value.getSyncExternalRefNo());
					obj.setFax(value.getFaxNumbers());
					obj.setMobilePhone(value.getMobilePhoneNumbers());
					
					if(!CommonService.IsNull(value.getNameThai()))
						obj.setName1(value.getNameThai());
					else if(!CommonService.IsNull(value.getNameEng()))
						obj.setName1(value.getNameEng());
					
					obj.setPaymentTerm(value.getPaymentTerm());
					obj.setPostcode(value.getPostalCode());
					obj.setSearchterm(value.getTitle());
					obj.setStreet(value.getAddressText());
					obj.setStreet4(value.getAddressText());
					obj.setStreet5(value.getTumbonName());
					obj.setTaxClassification(value.getTaxClassification());
					obj.setTaxcode1(value.getIdNo());
					obj.setTaxcode3(value.getTaxId());
					obj.setTelephone(value.getPhoneNumbers());
					obj.setTitle(value.getTitle());					
					obj.setUpdateby(value.getLastUpdBy());
					obj.setUpdateon(CommonService.ConvertDateToSAPStringDate(value.getLastUpdOn()));
					
					obj.setReconAccount(value.getReconAccount());
								
					obj.setProcessAction(processAction);
					obj.setSyncCreatedon(iSdCustomerOutb1Services.getCurrentDatabaseDate());
					obj.setSyncCreatedby(Userinfo.getUser());
					obj.setSyncIssync("N");
					obj.setMsgCode(STAGING_STATUS.SS.toString());
					obj.setMsgDesc("Write to staging success.");
					obj.setId(CommonService.IsNullRString(iSdCustomerOutb1Services.NextSequence()));
					obj.setInstanceNo(getCurrentAppsInstanceNo());
					obj.setLastedStampOn(iSdCustomerOutb1Services.getCurrentDatabaseDate());		
					
					lstx.add(obj);
				}
				
				iSdCustomerOutb1Services.saveOrUpdate(lstx);
				
				xmlResultback.setMsgcode("SS");
				xmlResultback.setMsgDescription("Write to Staging Success.");
				
				try{
					//Search Customer list by InstanceNo
					List<SdCustomerOutb1> lst = iSdCustomerOutb1Services.findByInstanceNo(getCurrentAppsInstanceNo(), new SdCustomerOutb1());
					logging.info("iSdCustomerOutb1Services Size=" + CommonService.getSize(lst));
					
					if(CommonService.getSize(lst) > 0){
						try{
							
							List<SdCustomerOutb1> lst1 = new ArrayList<>();
							for(SdCustomerOutb1 sdCustomerOutb1 : lst){
								SdCustomerOutb1 cusOutb1 = sdCustomerOutb1;
								
								 List<String> nameLst = iSdCustomerOutb1Services.NameSplitToSAP(sdCustomerOutb1.getName1());
								 cusOutb1.setName1(nameLst.get(0));
								 cusOutb1.setName2(nameLst.get(1));
								 cusOutb1.setName3(nameLst.get(2));
								 cusOutb1.setName4(nameLst.get(3));
								 
								 
								 List<String> streetLst = iSdCustomerOutb1Services.NameSplitToSAP(sdCustomerOutb1.getStreet());
								 cusOutb1.setStreet(streetLst.get(0));
								 cusOutb1.setStreet4(streetLst.get(1));
								 
								 lst1.add(cusOutb1);
							}
							
							logging.info("common size =" + CommonService.getSize(lst1));
							SapMessageReturn<SdCustomerOutb1> sapMessageReturn = new CustomerInterServices().SynchroToSap(lst1);
							
							if(sapMessageReturn != null){
								ResultStatus resultStatus = sapMessageReturn.getResultBacked().getResultStatus();
								if(resultStatus != null){
									List<SapMessage> sapMessageList = sapMessageReturn.getOutput();
									
									logging.info("sapMessageList size=" + CommonService.getSize(sapMessageList));
									if(CommonService.getSize(sapMessageList) > 0)
									{
										SapMessage sapMsg = sapMessageList.get(0);
										logging.info("SapMessage toString=" + sapMsg.toString());
										xmlResultback.setMsgcode(sapMsg.getMsgCode());
										xmlResultback.setMsgDescription(sapMsg.getMsgDesc());
										xmlResultback.setExtRefNo(sapMsg.getExtRefNo());
										xmlResultback.setExtRefKey(sapMsg.getExtRefKey());
									}
								}
								
								//Step Update Message to Staging Table
								List<SdCustomerOutb1> lstResultBack = iSdCustomerOutb1Services.UpdateBackSapMessage(sapMessageReturn.getOutput());
								logging.info("lstResultBack size=" + CommonService.getSize(lstResultBack));
								
								//Step Update Back to Promis Table
								try{
									if(CommonService.getSize(lstResultBack) > 0){
										Customer obj = iCustomerServices.findById(lstResultBack.get(0).getCustomer());
										if(obj != null)
										{
											obj.setSyncIsstaging("Y");
											obj.setSyncIssync("N");
											obj.setResendCount(obj.getResendCount() + 1);
											if(CommonService.IsNullRString(lstResultBack.get(0).getMsgCode()).equals("PS")){					
												obj.setSyncIssync("Y");	
											}
											
											iCustomerServices.saveOrUpdate(obj);
										}
									}
								}catch(Exception ex){
									ex.printStackTrace();
									xmlResultback.setMsgcode("EE");
									xmlResultback.setMsgDescription("" + ex.getMessage());
									logging.error(ex.getMessage());
									iSdCustomerOutb1Services.SaveErrorToStaging(getCurrentAppsInstanceNo(), STAGING_STATUS.EE, ex.getMessage());
									KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", ex.getMessage(), null, getCurrentAppsInstanceNo()));									
								}
							}
						}catch(Exception  ee){
							ee.printStackTrace();
							xmlResultback.setMsgcode(STAGING_STATUS.EE.toString());
							xmlResultback.setMsgDescription(ee.getMessage());
							
							KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", ee.getMessage(), null, getCurrentAppsInstanceNo()));
						}
					}else{
						xmlResultback.setMsgcode(STAGING_STATUS.EE.toString());
						xmlResultback.setMsgDescription("Find not found [instanceNo="+ getCurrentAppsInstanceNo() +"]!!!");
					}
					
				}catch(Exception e){
					e.printStackTrace();
					xmlResultback.setMsgcode("EE");
					xmlResultback.setMsgDescription("" + e.getMessage());
					logging.error(e.getMessage());
					iSdCustomerOutb1Services.SaveErrorToStaging(getCurrentAppsInstanceNo(), STAGING_STATUS.EE, e.getMessage());
					KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", CommonService.CutString(e.getMessage(), 2900), null, getCurrentAppsInstanceNo()));
				}
			}else{
				xmlResultback.setMsgcode("EE");
				xmlResultback.setMsgDescription("Authentication is fail.");
			}
		}catch(Exception e){
			e.printStackTrace();
			xmlResultback.setMsgcode("EE");
			xmlResultback.setMsgDescription("" + e.getMessage());
			logging.error(e.getMessage());
			iSdCustomerOutb1Services.SaveErrorToStaging(getCurrentAppsInstanceNo(), STAGING_STATUS.EE, e.getMessage());
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", CommonService.CutString(e.getMessage(), 2900), null, getCurrentAppsInstanceNo()));
		}
		
		return(ToXml(xmlResultback));
	}
	
	@RequestMapping(value="search/json", method = RequestMethod.GET, headers="accept=application/json")
	@ResponseBody
	public List<SdCustomerOutb1> Search(
										@RequestParam(value="stagingId", required=false) String stagingId,
										@RequestParam(value="customerCode", required=false) String customerCode,
										@RequestParam(value="customerName", required=false) String name,
										@RequestParam(value="idNo", required=false) String idNo,	
										@RequestParam(value="taxId", required=false) String taxId,										
										@RequestParam(value="instanceNo", required=false) String instanceNo,
										@RequestParam(value="syncCreatedOnStart", required=false) String syncCreatedOnStart,
										@RequestParam(value="syncCreatedOnEnd", required=false) String syncCreatedOnEnd,
										@RequestParam(value="maxResult", required=true) String maxResult,
										HttpServletRequest request, 
										HttpServletResponse response) throws Exception {
		
		logging.info("search/json {Search} ::: method = RequestMethod.GET");
		setCurrentAppsInstanceNo();
		KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
		
		if(!UserLoginValidation((request))) {
			response.setStatus(500);
			return null;
		}
		
		try {
			
			if(!UserLoginValidation((request)))
				throw new Exception("Can't Search, Please Login first !!!!");
			
			logging.info("stagingId --> " +  stagingId); 
			logging.info("customerCode --> " +  customerCode);
			logging.info("customerCode --> " +  Encoding(name));
			logging.info("idNo --> " +  idNo); 
			logging.info("taxId --> " +  taxId);
			logging.info("instanceNo --> " +  instanceNo); 
			logging.info("syncCreatedOnStart --> " +  syncCreatedOnStart);
			logging.info("syncCreatedOnEnd --> " +  syncCreatedOnEnd);
			logging.info("maxResult --> " +  maxResult);
			
			if(CommonService.IsNull(syncCreatedOnStart))
				syncCreatedOnStart = "1980-01-01";
			
			if(CommonService.IsNull(syncCreatedOnEnd))
				syncCreatedOnStart = "2017-12-31";

			int maxResultInt = -1;
			if(!CommonService.IsNull(maxResult))
				maxResultInt = (Integer.parseInt(CommonService.IsNullRZero(maxResult)) == 0) ? -1 : Integer.parseInt(CommonService.IsNullRZero(maxResult));
			
			List<SdCustomerOutb1> lst = iSdCustomerOutb1Services.Search(stagingId, customerCode, Encoding(name),  idNo, taxId, instanceNo, syncCreatedOnStart, syncCreatedOnEnd, maxResultInt);		
			logging.info("SdCustomerOutb1 Size = " + CommonService.getSize(lst));
			
			if(CommonService.getSize(lst) > 0) 
				return lst;
			
		} catch (Exception e) {
			logging.error(e.getMessage());
			e.printStackTrace();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "E", e.getMessage(), null, getCurrentAppsInstanceNo()));
			throw e;
		}
		
		return null;
	}

}
